ifGame = 0;
var game;
let x = new Array();
let y = new Array();
var foodFollowers = new Array();
var goodemitter = new Phaser.Events.EventEmitter();
var bademitter = new Phaser.Events.EventEmitter();
var foodImgsCount = 3;//食物图片种类
var obstacleImgsCount = 3;//障碍物图片数量
var fullMarks = 8;//满分
var lifeNum = 5;//机会次数
var roleSpeed = 10;//主角移动速度
var foodamount=12;

class SceneA extends Phaser.Scene {
				
			    constructor ()
			    {
					
			        super('Gamescene');
			    }
			    preload ()
			    {
					if(charactorID == 2)
			         this.load.image('move', 'imgs/mainCharacter/cuteballs/cat.png');
					 else
					 this.load.image('move','imgs/mainCharacter/cuteballs/mouse01.png');
					var i = 1;
					for(var i = 0;i < foodImgsCount;i++){
						this.load.image("food"+i,'imgs/food/set1-'+i+'.png');
					}
					for(var i = 0;i < obstacleImgsCount;i++){
						this.load.image("Obstacle"+i,'imgs/injurant/rubbishSet1/waste'+i+'.png');
					}
					
			    }
			    create ()
			    {
					
					this.food=new Array();
					this.obstacles = new Array();
                    this.b=0;
					let canMove= false;
					
					this.dragger=this.add.sprite(300, 300, 'move');
					this.dragger.setScale(0.8,0.8);//设置主角大小
					
					for (var i=0;i<foodamount;i++){
						var imgIndex = i % foodImgsCount;
						this.food[i]=this.add.sprite(-100,-100,'food'+imgIndex);
						this.food[i].setScale(0.4,0.4);//设置食物大小
					}
					
					for (var i=0;i<foodamount;i++){
						var imgIndex = i % obstacleImgsCount;
						this.obstacles[i]=this.add.sprite(-100,-100,"Obstacle"+imgIndex);
					}
					var pointer = this.input.activePointer;
			        this.input.on('pointerup', this.clickHandler1, this);
			        this.input.on("pointerdown",this.clickHandler2,this);
					
			    }
			
			    update(){
                    this.b++;
			    	
					let draggermovex=Math.cos(this.a)*roleSpeed;
					let draggermovey=Math.sin(this.a)*roleSpeed;
					if (this.dragger.x > 960){
						draggermovex=0;
						this.dragger.x-=1;
					};
					if(this.dragger.x<0){
						draggermovex=0;
						this.dragger.x+=1;
					}
					if (this.dragger.y > 1440){
						draggermovey=0;
						this.dragger.y-=1;
					}
					if(this.dragger.y < 0){
						draggermovey=0;
						this.dragger.y+=1;
					}
					if(this.canMove){
						this.dragger.x+=draggermovex;
						this.dragger.y+=draggermovey;
					}
					if(this.b>100){
						
						for(var i=0;i<this.b/100-1;i++){
							if(this.food[i]==null)continue;
							if(x[i]!=null&&this.food[i].x!=-200){
						      this.food[i].x=x[i].x;
						      this.food[i].y=x[i].y;
						    }
							if(y[i]!=null&&this.obstacles[i].x!=-200){
							  this.obstacles[i].x=y[i].x;
							  this.obstacles[i].y=y[i].y;
							}
						}
						for(var i=0;i<foodamount;i++){
							var a=(this.food[i].x-this.dragger.x)*(this.food[i].x-this.dragger.x)+(this.food[i].y-this.dragger.y)*(this.food[i].y-this.dragger.y);//主角和food的判断距离
							var b=(this.obstacles[i].x-this.dragger.x)*(this.obstacles[i].x-this.dragger.x)+(this.obstacles[i].y-this.dragger.y)*(this.obstacles[i].y-this.dragger.y);//主角和obstacles的判断距离
							if(a<2500){//距离少于一定的值的话就杀死food
								goodemitter.emit('eatonefood',i);//提交一个事件，名字叫eatonefood，在sceneC接收
							    this.killsprite(this.food[i]);
							}
							if(b<2500){
								bademitter.emit("eatoneshit",i);//提交一个事件，名字叫eatoneshit，在sceneC接收
								this.killsprite(this.obstacles[i]);
							}
						}
					}
			    }
				
				killsprite(a){
					a.x=-200;
					a.y=-200
				}
				
			    clickHandler1 (){
					//console.log("pointerup");
					this.canMove=true;
					
			    }
				
				clickHandler2(){
					//console.log("pointerdown");
					if(this.input.x>this.dragger.x){
					      this.a=Math.atan((this.input.y-this.dragger.y)/(this.input.x-this.dragger.x));
					}
					if(this.input.x<this.dragger.x){
					      this.a=Math.PI+Math.atan((this.input.y-this.dragger.y)/(this.input.x-this.dragger.x));
					}
					this.canMove=false;
				}
			}
			
class SceneB extends Phaser.Scene {
			
			    constructor (){
			        super({ key: 'UIScene', active: true });
			    }
				create(){
					this.count=0;
					this.info = this.add.text(10, 10, 'Score: 0', { font: '48px Arial', fill: '#000000' });
					let ourGame = this.scene.get('GameScene');
					goodemitter.on('eatonefood', this.goodhandler, this)
					bademitter.on("eatoneshit",this.badhandler,this)
				}
				goodhandler(){
					this.count++;
					this.info.setText("Score："+this.count);
					var pg=document.getElementById('pg');
					if (this.count < fullMarks) {
					    pg.value = (this.count/fullMarks) * 100;
					}
					if(this.count >= fullMarks){
						console.log('success');
						// game.scale.setGameSize(0, 0);
						 game.destroy();
						goToSuccess();
					}
					
				}
				badhandler(){  
					//this.count--;
					this.info.setText("Score:"+this.count);
					//损失分值
					var pg=document.getElementById('pg');
					if (this.count < fullMarks) {
					    pg.value = (this.count/fullMarks) * 100;
					}
					//损失生命值
					var pg0=document.getElementById('pg0');
					if(pg0.value > 0)
					pg0.value = pg0.value - 100/lifeNum;
					if(pg0.value <= 0){
						console.log('failure');
						//game.scale.setGameSize(0, 0);
						game.destroy();
						goToFailure();
					}
					
					
				}
			}
			
class SceneC extends Phaser.Scene{
				constructor(){
					super({key:"foodtrain",active:true});
				}
				preload(){
				}
				create ()
				{
					
					this.paths = new Array();
					this.secondaryPaths = new Array();//辅助路径
					this.followers = foodFollowers;
					this.followrsPath = new Array();
					this.obstacles = new Array();//障碍物
					
					//ifStart控制食物是否开始生成,FollowersCount设置食物个数,timeInterval设置每两个食物生成的时间间隔
					this.counts = 0, this.j = 0, this.ifStart = true, this.obstacleSpeed = 8000;
					this.FollowersCount = foodamount, this.timeInterval = 50, this.followerSpeed = 4000;
					this.secondaryPathsDistance = 60;//辅助路径与主路径的距离
				    this.graphics = this.add.graphics();
				    //  路径设置
				     this.paths[0] = new Phaser.Curves.Path(100, 1000);//武汉地铁线路4号线
				    				    this.paths[1] = new Phaser.Curves.Path(150, 350);//武汉地铁线路2号线
				    				    this.paths[2] = new Phaser.Curves.Path(850, 300);//武汉地铁线路3号线
				    					this.paths[1].lineTo(410,840);
				    					this.paths[1].lineTo(410,890);
				    					this.paths[1].lineTo(450,920);
				    					this.paths[1].lineTo(490,920);
				    					this.paths[1].lineTo(750,1300);
				    					this.paths[1].lineTo(920,1300);
				    					this.paths[2].lineTo(550,840);
				    					this.paths[2].lineTo(350,840);
				    					this.paths[2].lineTo(50,1530);
				    				    this.paths[0].lineTo(320, 1300);
				    				    this.paths[0].lineTo(600, 1300);
				    				    this.paths[0].lineTo(850, 780);
				    					this.paths[0].lineTo(900, 780);
					//创建辅助路径
					this.secondaryPaths = createSecondaryPaths(this.paths,this.secondaryPathsDistance);
					
					//吃食物和碰撞障碍物的响应
					//goodemitter.on('eatonefood', this.eatFood, this)
					//bademitter.on("eatoneshit",this.badhandler,this)
				}
				update ()
				{
					//console.log("updateC");
					this.counts++;
				    this.graphics.clear();
				    this.graphics.lineStyle(10, 0xffffff, 0.5);
					
					for(i = 0; i < this.paths.length ;i++)
					{//绘制路径
						this.paths[i].draw(this.graphics);
						//this.secondaryPaths[i*2].draw(this.graphics);
						//this.secondaryPaths[i*2+1].draw(this.graphics);
					}
				    this.graphics.fillStyle(0xff0000, 0);	 
					 //添加食物
					if(this.counts == 100 && this.ifStart && this.followers.length<this.FollowersCount){
						    this.counts = 0 ;
							this.followers[this.j] = { t: 0, vex: new Phaser.Math.Vector2() };
							console.log(this.followers.length);
							
							this.tweens.add({
						  		targets: this.followers[this.j],
						  		t: 1,
						  		ease: 'Sine.easeInOut',
						  		duration: this.followerSpeed,
						  		yoyo: true,
						  		repeat: -1
						  	});
							this.followrsPath[this.j] = parseInt( Math.random() * this.paths.length);
							this.j++;
							//创建障碍物测试，参数（场景，follower)
							createObstacle(this,this.followers[this.j - 1]);
					}
					
					//绘制食物
					for(var i = 0 ;i< this.followers.length;i++){
							  if(this.followers[i] !=null){
								  this.paths[this.followrsPath[i]].getPoint(this.followers[i].t, this.followers[i].vex);
								  this.graphics.fillCircle(this.followers[i].vex.x, this.followers[i].vex.y, 12);
								  x[i]=this.followers[i].vex;
					          }
							  
					}
					
					//绘制障碍物
					for(var i = 0 ;i< this.obstacles.length;i++){
							  if(this.obstacles[i] !=null && !isNaN(this.obstacles[i].followPathNum)){
								  this.secondaryPaths[this.obstacles[i].followPathNum].getPoint(this.obstacles[i].t, this.obstacles[i].vex);
								  this.graphics.fillCircle(this.obstacles[i].vex.x, this.obstacles[i].vex.y, 12);
								  y[i]=this.obstacles[i].vex;
					          }
					}
					
				}
				
			}
			
function createSecondaryPaths(mainPaths,distance){
				var secondaryPaths = new Array();
				for(i = 0; i< mainPaths.length;i++){
					//创建Path
					if(mainPaths[i].curves[0].p0.x == mainPaths[i].curves[0].p1.x){
					 //第一段斜率不存在	
					 mainPaths[i].curves[0].k = null;
					 x1 = mainPaths[i].curves[j].p1.x - distance;
					 y1 = mainPaths[i].curves[j].p1.y ;
					 secondaryPaths[i*2] = new Phaser.Curves.Path(x1,y1);
					 x1 = mainPaths[i].curves[j].p1.x + distance;
					 y1 = mainPaths[i].curves[j].p1.y;
					 secondaryPaths[i*2 + 1] = new Phaser.Curves.Path(x1,y1);
					}
					else{
						//第一段斜率存在
						mainPaths[i].curves[0].k = ((mainPaths[i].curves[0].p1.y - mainPaths[i].curves[0].p0.y)/(mainPaths[i].curves[0].p1.x - mainPaths[i].curves[0].p0.x));
						
						if(mainPaths[i].curves[0].k == 0){
							//第一段斜率为0
							x1 = mainPaths[i].curves[j].p1.x;
							y1 = mainPaths[i].curves[j].p1.y - distance;
							secondaryPaths[i*2] = new Phaser.Curves.Path(x1,y1);
							x1 = mainPaths[i].curves[j].p1.x;
							y1 = mainPaths[i].curves[j].p1.y + distance;
							secondaryPaths[i*2 + 1] = new Phaser.Curves.Path(x1,y1);
						}
						else{
							//第一段斜率不为0
							if(mainPaths[i].curves[0].k < 0)
								signal = -1;
							else 
								signal = 1;
							k1 = -1/mainPaths[i].curves[0].k;
							x1 = mainPaths[i].curves[0].p0.x - distance * Math.cos(Math.atan(k1))*signal;
							y1 = mainPaths[i].curves[0].p0.y - distance * Math.sin(Math.atan(k1))*signal;
							secondaryPaths[i*2] = new Phaser.Curves.Path(x1,y1);
							x1 = mainPaths[i].curves[0].p0.x + distance * Math.cos(Math.atan(k1))*signal;
							y1 = mainPaths[i].curves[0].p0.y + distance * Math.sin(Math.atan(k1))*signal;
							secondaryPaths[i*2+1] = new Phaser.Curves.Path(x1,y1);
						}
					}
					//处理中间段的起点
					for(j=1;j<mainPaths[i].curves.length;j++){
						if(mainPaths[i].curves[j].p0.x == mainPaths[i].curves[j].p1.x){
						 //中间段斜率不存在
						 mainPaths[i].curves[j].k = null;
						 x1 = mainPaths[i].curves[j].p0.x - distance;
						 y1 = mainPaths[i].curves[j].p0.y ;
						 secondaryPaths[i*2].lineTo(x1,y1);
						 x1 = mainPaths[i].curves[j].p0.x + distance;
						 y1 = mainPaths[i].curves[j].p0.y;
						 secondaryPaths[i*2 + 1].lineTo(x1,y1);
						}
						else{
							//中间段斜率存在
							mainPaths[i].curves[j].k = ((mainPaths[i].curves[j].p1.y - mainPaths[i].curves[j].p0.y)/(mainPaths[i].curves[j].p1.x - mainPaths[i].curves[j].p0.x));
							
							if(mainPaths[i].curves[j-1].k == null)
							//上一段的斜率不存在
								angleDifference = Math.atan(mainPaths[i].curves[j].k) - Math.PI/2;
							//上一段斜率存在
					        angleDifference = Math.atan(mainPaths[i].curves[j].k) - Math.atan(mainPaths[i].curves[j-1].k);
							newAngle = (Math.PI - angleDifference)/2;
							newAngle2 = newAngle - (Math.PI/2 - Math.atan(mainPaths[i].curves[j].k));
							distance2 = distance/Math.sin(newAngle);
							
							x1 = mainPaths[i].curves[j].p0.x - distance2 * Math.sin(newAngle2);
							y1 = mainPaths[i].curves[j].p0.y + distance2 * Math.cos(newAngle2);
							secondaryPaths[i*2].lineTo(x1,y1);
							x1 = mainPaths[i].curves[j].p0.x + distance2 * Math.sin(newAngle2);
							y1 = mainPaths[i].curves[j].p0.y - distance2 * Math.cos(newAngle2);
							secondaryPaths[i*2 + 1].lineTo(x1,y1);
								
						}
					}
					//处理最后一段的终点
					j = mainPaths[i].curves.length -1;//最后一段
					if(mainPaths[i].curves[j].p0.x == mainPaths[i].curves[j].p1.x){
					 //最后一段斜率不存在	
					 mainPaths[i].curves[j].k = null;
					 x1 = mainPaths[i].curves[j].p1.x - distance;
					 y1 = mainPaths[i].curves[j].p1.y ;
					 secondaryPaths[i*2].lineTo(x1,y1);
					 x1 = mainPaths[i].curves[j].p1.x + distance;
					 y1 = mainPaths[i].curves[j].p1.y;
					 secondaryPaths[i*2 + 1].lineTo(x1,y1);
					 
					}
					else{
						//最后一段斜率存在
						mainPaths[i].curves[j].k = ((mainPaths[i].curves[j].p1.y - mainPaths[i].curves[j].p0.y)/(mainPaths[i].curves[j].p1.x - mainPaths[i].curves[j].p0.x));
						if(mainPaths[i].curves[j].k == 0){
							//最后一段斜率为0
							x1 = mainPaths[i].curves[j].p1.x;
							y1 = mainPaths[i].curves[j].p1.y - distance;
							secondaryPaths[i*2].lineTo(x1,y1);
							x1 = mainPaths[i].curves[j].p1.x;
							y1 = mainPaths[i].curves[j].p1.y + distance;
							secondaryPaths[i*2 + 1].lineTo(x1,y1);
						}
						else{
							//最后一段斜率不为0
							if(mainPaths[i].curves[j].k < 0)
							signal = -1;
							else 
							signal = 1;
							k1 = -1/mainPaths[i].curves[j].k;
							x1 = mainPaths[i].curves[j].p1.x - distance * Math.cos(Math.atan(k1))*signal;
							y1 = mainPaths[i].curves[j].p1.y - distance * Math.sin(Math.atan(k1))*signal;
							secondaryPaths[i*2].lineTo(x1,y1);
							x1 = mainPaths[i].curves[j].p1.x + distance * Math.cos(Math.atan(k1))*signal;
							y1 = mainPaths[i].curves[j].p1.y + distance * Math.sin(Math.atan(k1))*signal;
							secondaryPaths[i*2 + 1].lineTo(x1,y1);
						}
					}
					
					
					
					
				}
				return secondaryPaths;
			}
var turn = 0;//createObstacle专用变量
function createObstacle(thisScene,follower){
				index = thisScene.followers.indexOf(follower);
				pathOfThisFollower = thisScene.followrsPath[index];
				newObstacle = { t: 0, vex: new Phaser.Math.Vector2() };
				newObstacle.followPath = thisScene.secondaryPaths[pathOfThisFollower * 2 + turn];
				newObstacle.followPathNum = pathOfThisFollower * 2 + turn;
				turn = 1 - turn;
				thisScene.obstacles[thisScene.obstacles.length] = newObstacle;
				thisScene.tweens.add({
					targets: newObstacle,
					t: 1,
					ease: 'Sine.easeInOut',
					duration: thisScene.obstacleSpeed,
					yoyo: true,
					repeat: -1
				});
		
			}
			
let config = {
	 type: Phaser.CANVAS,
	width: "100%",
	 height: "100%",
	 transparent:true,
	 parent: 'phaser-example',
	 scene: [ SceneA,SceneB,SceneC]
	};

function gameBegin(){
	if(ifGame == 0){
		document.getElementsByClassName('scoreManage')[0].style.display = 'block';
		game = new Phaser.Game(config);
		ifGame = 1;
		document.getElementById('return').style.top ="130px";
	}
	
}